// 测评分数管理模块
const EvaluationScoreModule = {
    currentTab: 'dept-indicators',

    // 初始化
    init() {
        // 加载指标下拉框数据
        this.loadIndicatorOptions();
        // 加载部门下拉框数据
        this.loadDeptOptions();
        this.switchTab('dept-indicators');
    },

    // 加载指标下拉框数据
    loadIndicatorOptions() {
        CommonModule.apiRequest('/indicators/options')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data) {
                    this.populateIndicatorSelect(data.data);
                } else {
                    console.error('加载指标选项失败:', data.message);
                }
            })
            .catch(error => {
                console.error('加载指标选项失败:', error);
            });
    },

    // 填充指标下拉框
    populateIndicatorSelect(indicators) {
        // 部门指标分数页面的指标下拉框
        const deptIndicatorSelect = document.getElementById('deptIndicatorTypeSearch');
        if (deptIndicatorSelect) {
            // 清空现有选项（保留"全部指标"选项）
            deptIndicatorSelect.innerHTML = '<option value="">全部指标</option>';
            
            // 只添加对部门的指标（khfs=1）
            indicators.filter(indicator => indicator.khfs === '1').forEach(indicator => {
                const option = document.createElement('option');
                option.value = indicator.zbbh;
                option.textContent = indicator.zbmc;
                deptIndicatorSelect.appendChild(option);
            });
        }

        // 教师指标分数页面的指标下拉框
        const teacherIndicatorSelect = document.getElementById('teacherIndicatorTypeSearch');
        if (teacherIndicatorSelect) {
            // 清空现有选项（保留"全部指标"选项）
            teacherIndicatorSelect.innerHTML = '<option value="">全部指标</option>';
            
            // 只添加对教师的指标（khfs=0）
            indicators.filter(indicator => indicator.khfs === '0').forEach(indicator => {
                const option = document.createElement('option');
                option.value = indicator.zbbh;
                option.textContent = indicator.zbmc;
                teacherIndicatorSelect.appendChild(option);
            });
        }
    },

    // 加载部门下拉框数据
    loadDeptOptions() {
        CommonModule.apiRequest('/dept/options')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data) {
                    this.populateDeptSelect(data.data);
                } else {
                    console.error('加载部门选项失败:', data.message);
                }
            })
            .catch(error => {
                console.error('加载部门选项失败:', error);
            });
    },

    // 填充部门下拉框
    populateDeptSelect(depts) {
        // 教师总分页面的部门下拉框
        const teacherScoreDeptSelect = document.getElementById('teacherScoreDeptSearch');
        if (teacherScoreDeptSelect) {
            // 清空现有选项（保留"全部部门"选项）
            teacherScoreDeptSelect.innerHTML = '<option value="">全部部门</option>';
            
            // 添加部门选项
            depts.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept.bmbh;
                option.textContent = dept.bmmc;
                teacherScoreDeptSelect.appendChild(option);
            });
        }

        // 部门指标分数页面的部门搜索框（如果需要的话）
        // 注意：部门指标分数页面使用的是文本输入框，不是下拉框
        
        // 部门总分页面的部门下拉框（如果存在的话）
        const deptTotalScoreDeptSelect = document.getElementById('deptTotalScoreDeptSearch');
        if (deptTotalScoreDeptSelect) {
            // 清空现有选项（保留"全部部门"选项）
            deptTotalScoreDeptSelect.innerHTML = '<option value="">全部部门</option>';
            
            // 添加部门选项
            depts.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept.bmbh;
                option.textContent = dept.bmmc;
                deptTotalScoreDeptSelect.appendChild(option);
            });
        }
    },

    // Tab切换（兼容性方法）
    switchScoreTab(tabName) {
        this.switchTab(tabName);
    },

    // Tab切换
    switchTab(tabName) {
        this.currentTab = tabName;
        
        // 切换Tab活动状态
        document.querySelectorAll('#evaluation-score-management .tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('#evaluation-score-management .tab-content').forEach(content => {
            content.classList.remove('active');
        });

        // 激活选中的Tab
        const targetTab = document.querySelector(`#evaluation-score-management .tab[onclick*="${tabName}"]`);
        if (targetTab) {
            targetTab.classList.add('active');
        }
        // 正确的Tab内容ID映射
        const tabContentMapping = {
            'dept-indicators': 'dept-indicators-score-tab',
            'dept-total': 'dept-total-score-tab',
            'teacher-indicators': 'teacher-indicators-score-tab',
            'teacher-total': 'teacher-total-score-tab',
            'calculation': 'calculation-tab'
        };
        
        const targetContent = document.getElementById(tabContentMapping[tabName]);
        if (targetContent) {
            targetContent.classList.add('active');
        }

        // 加载对应数据
        switch(tabName) {
            case 'dept-indicators':
                this.loadDeptIndicatorScores();
                break;
            case 'dept-total':
                this.loadDeptTotalScores();
                break;
            case 'teacher-indicators':
                this.loadTeacherIndicatorScores();
                break;
            case 'teacher-total':
                this.loadTeacherTotalScores();
                break;
            case 'calculation':
                // 计算页面不需要加载数据
                break;
        }
    },

    // ========== 部门指标分数 ==========
    loadDeptIndicatorScores(page = 1) {
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', 10);

        // 获取搜索条件
        const deptName = document.getElementById('deptIndicatorScoreSearch')?.value;
        const indicatorId = document.getElementById('deptIndicatorTypeSearch')?.value;
        if (deptName) params.append('deptName', deptName);
        if (indicatorId) params.append('indicatorId', indicatorId);

        CommonModule.apiRequest(`/score/dept-indicator-scores?${params}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderDeptIndicatorScoresTable(data.data.list || []);
                    if (data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 10);
                        CommonModule.createPagination('deptIndicatorScoresPagination', totalPages, page, (p) => this.loadDeptIndicatorScores(p));
                    } else {
                        // 如果没有数据，显示提示信息
                        this.renderDeptIndicatorScoresTable([]);
                        this.showNoDataMessage('部门指标分数');
                    }
                } else {
                    // 传递服务器返回的具体错误信息
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载部门指标分数');
                    this.renderDeptIndicatorScoresTable([]);
                }
            })
            .catch(error => {
                console.error('加载部门指标分数失败:', error);
                this.renderDeptIndicatorScoresTable([]);
                this.showNoDataMessage('部门指标分数');
            });
    },

    renderDeptIndicatorScoresTable(scores) {
        const tbody = document.querySelector('#deptIndicatorScoresTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (scores && scores.length > 0) {
            scores.forEach(score => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${score.bmbh || score.bcpbm || ''}</td>
                    <td>${score.bmmc || score.bcpbm || ''}</td>
                    <td>${score.zbbh || score.cpzbbh || ''}</td>
                    <td>${score.cpqzbh || ''}</td>
                    <td>${score.cpqzmc || ''}</td>
                    <td>${score.cpzbqz || ''}</td>
                    <td>${score.score || '0'}</td>
                    <!--td>
                        <button class="btn btn-primary btn-small" onclick="EvaluationScoreModule.viewDeptIndicatorScore('${score.bh}')">查看详情</button>
                    </td-->
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="8">暂无数据</td></tr>';
        }
    },

    // 搜索部门指标分数
    searchDeptIndicatorScores() {
        this.loadDeptIndicatorScores(1);
    },

    // 导出部门指标分数
    exportDeptIndicatorScores() {
        window.open(CommonModule.globalConfig.apiBase + '/score/export/dept-indicator-scores');
    },

    // 导出部门人事数据
    exportDeptPersonnelData() {
        window.open(CommonModule.globalConfig.apiBase + '/score/export/dept-personnel-data');
    },

    // 搜索教师指标分数
    searchTeacherIndicatorScores() {
        this.loadTeacherIndicatorScores(1);
    },

    // 导出教师指标分数
    exportTeacherIndicatorScores() {
        window.open(CommonModule.globalConfig.apiBase + '/score/export/teacher-indicator-scores');
    },

    // 导出教师行政数据
    exportTeacherAdminData() {
        window.open(CommonModule.globalConfig.apiBase + '/score/export/teacher-admin-data');
    },

    // 导出教师教师数据
    exportTeacherTeacherData() {
        window.open(CommonModule.globalConfig.apiBase + '/score/export/teacher-teacher-data');
    },

    // 搜索教师总分
    searchTeacherTotalScores() {
        this.loadTeacherTotalScores(1);
    },

    // 导出教师总分
    exportTeacherTotalScores() {
        window.open(CommonModule.globalConfig.apiBase + '/score/export/teacher-total-scores');
    },

    // 显示无数据消息
    showNoDataMessage(type) {
        const tbody = document.querySelector('#deptIndicatorScoresTableContent table tbody');
        if (tbody) {
            tbody.innerHTML = `<tr><td colspan="7" class="empty">暂无${type}数据，请先执行分数计算</td></tr>`;
        }
    },

    viewDeptIndicatorScore(bh) {
        console.log('查看部门指标分数详情:', bh);
        this.showDeptIndicatorScoreDetailModal(bh);
    },

    showDeptIndicatorScoreDetailModal(bh) {
        // 显示模态框
        const modal = document.getElementById('deptIndicatorScoreDetailModal');
        if (modal) {
            modal.classList.add('show');
            
            // 重置表格内容
            const tbody = document.getElementById('deptIndicatorScoreDetailTableBody');
            if (tbody) {
                tbody.innerHTML = '<tr><td colspan="4" class="loading">加载中...</td></tr>';
            }
            
            // 加载部门指标分数详细信息
            this.loadDeptIndicatorScoreDetail(bh);
        }
    },

    loadDeptIndicatorScoreDetail(bh) {
        CommonModule.apiRequest(`/score/dept-indicator-scores/${bh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    const detail = data.data;
                    
                    // 更新基本信息
                    document.getElementById('detailIndicatorDeptCode').textContent = detail.bmbh || detail.bcpbm || '';
                    document.getElementById('detailIndicatorDeptName').textContent = detail.bmmc || detail.bcpbm || '';
                    document.getElementById('detailIndicatorCode').textContent = detail.cpzbbh || '';
                    document.getElementById('detailIndicatorName').textContent = detail.zbmc || '';
                    document.getElementById('detailIndicatorWeight').textContent = (detail.cpzbqz || 0) + '';
                    document.getElementById('detailIndicatorWeightCode').textContent = detail.cpqzbh || '';
                    document.getElementById('detailIndicatorScore').textContent = (detail.score || 0) + '分';
                    
                    // 更新测评明细
                    this.renderDeptIndicatorScoreDetailTable(detail.evaluationDetails || []);
                } else {
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载部门指标分数详情');
                    this.renderDeptIndicatorScoreDetailTable([]);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载部门指标分数详情');
                this.renderDeptIndicatorScoreDetailTable([]);
            });
    },

    renderDeptIndicatorScoreDetailTable(evaluationDetails) {
        const tbody = document.getElementById('deptIndicatorScoreDetailTableBody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (evaluationDetails && evaluationDetails.length > 0) {
            evaluationDetails.forEach(detail => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${detail.cprbm || ''}</td>
                    <td>${detail.cprxm || detail.cprbm || ''}</td>
                    <td>${detail.totalscore || '0'}分</td>
                    <td>${detail.cprq || ''}</td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="4" class="empty">暂无测评明细数据</td></tr>';
        }
    },

    closeDeptIndicatorScoreDetailModal() {
        const modal = document.getElementById('deptIndicatorScoreDetailModal');
        if (modal) {
            modal.classList.remove('show');
        }
    },

    exportDeptIndicatorScoreDetail() {
        const deptCode = document.getElementById('detailIndicatorDeptCode').textContent;
        const indicatorCode = document.getElementById('detailIndicatorCode').textContent;
        if (deptCode && indicatorCode) {
            window.location.href = CommonModule.globalConfig.apiBase + `/export/dept-indicator-score-detail/${encodeURIComponent(deptCode)}/${encodeURIComponent(indicatorCode)}`;
        } else {
            alert('无法导出：信息不完整');
        }
    },

    viewDeptScore(deptCode) {
        console.log('查看部门总分详情:', deptCode);
        this.showDeptScoreDetailModal(deptCode);
    },

    showDeptScoreDetailModal(deptCode) {
        // 显示模态框
        const modal = document.getElementById('deptScoreDetailModal');
        if (modal) {
            modal.classList.add('show');
            
            // 重置表格内容
            const tbody = document.getElementById('deptScoreDetailTableBody');
            if (tbody) {
                tbody.innerHTML = '<tr><td colspan="8" class="loading">加载中...</td></tr>';
            }
            
            // 加载部门详细信息
            this.loadDeptScoreDetail(deptCode);
        }
    },

    loadDeptScoreDetail(deptCode) {
        // 获取部门基本信息和总分
        Promise.all([
            CommonModule.apiRequest(`/score/dept/detail/${encodeURIComponent(deptCode)}`),
            CommonModule.apiRequest(`/score/dept-indicator-scores/detail/${encodeURIComponent(deptCode)}`)
        ])
        .then(([deptResponse, scoresResponse]) => Promise.all([deptResponse.json(), scoresResponse.json()]))
        .then(([deptData, scoresData]) => {
            // 更新部门基本信息
            if (deptData.code === 200 && deptData.data) {
                const dept = deptData.data;
                document.getElementById('detailDeptCode').textContent = dept.bmbh || deptCode;
                document.getElementById('detailDeptName').textContent = dept.bmmc || dept.bcpbm || '未知部门';
                document.getElementById('detailTotalScore').textContent = (dept.totalScore || 0) + '分';
                document.getElementById('detailRanking').textContent = dept.ranking || '未排名';
            } else {
                // 如果获取部门信息失败，使用默认值
                document.getElementById('detailDeptCode').textContent = deptCode;
                document.getElementById('detailDeptName').textContent = '未知部门';
                document.getElementById('detailTotalScore').textContent = '0分';
                document.getElementById('detailRanking').textContent = '未排名';
            }
            
            // 更新指标分数明细
            if (scoresData.code === 200 && scoresData.data) {
                this.renderDeptScoreDetailTable(scoresData.data);
            } else {
                this.renderDeptScoreDetailTable([]);
            }
        })
        .catch(error => {
            console.error('加载部门分数详情失败:', error);
            // 显示错误信息
            document.getElementById('detailDeptCode').textContent = deptCode;
            document.getElementById('detailDeptName').textContent = '加载失败';
            document.getElementById('detailTotalScore').textContent = '0分';
            document.getElementById('detailRanking').textContent = '未排名';
            
            const tbody = document.getElementById('deptScoreDetailTableBody');
            if (tbody) {
                tbody.innerHTML = '<tr><td colspan="8" class="error">加载失败，请稍后重试</td></tr>';
            }
        });
    },

    renderDeptScoreDetailTable(scores) {
        const tbody = document.getElementById('deptScoreDetailTableBody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (scores && scores.length > 0) {
            scores.forEach(score => {
                const row = document.createElement('tr');
                const scoreValue = parseFloat(score.score || 0);
                const maxScore = parseFloat(score.maxScore || score.totalScore || 100);
                const scoreRate = maxScore > 0 ? ((scoreValue / maxScore) * 100).toFixed(1) + '%' : '0%';
                
                row.innerHTML = `
                    <td>${score.zbbh || score.indicatorCode || ''}</td>
                    <td>${score.zbmc || score.indicatorName || ''}</td>
                    <td>${score.khdbh || score.pointCode || ''}</td>
                    <td>${score.khdmc || score.pointName || ''}</td>
                    <td class="score-value">${scoreValue}分</td>
                    <td>${maxScore}分</td>
                    <td class="score-rate">${scoreRate}</td>
                    <td>${score.cprq || score.evaluationDate || ''}</td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="8" class="empty">暂无指标分数数据</td></tr>';
        }
    },

    closeDeptScoreDetailModal() {
        const modal = document.getElementById('deptScoreDetailModal');
        if (modal) {
            modal.classList.remove('show');
        }
    },

    exportDeptScoreDetail() {
        const deptCode = document.getElementById('detailDeptCode').textContent;
        if (deptCode && deptCode !== '未知部门') {
            window.location.href = CommonModule.globalConfig.apiBase + `/export/dept-score-detail/${encodeURIComponent(deptCode)}`;
        } else {
            alert('无法导出：部门信息不完整');
        }
    },

    searchDeptIndicatorScores() {
        this.loadDeptIndicatorScores(1);
    },

    exportDeptIndicatorScores() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/dept-indicator-scores';
    },

    // ========== 部门总分 ==========
    loadDeptTotalScores(page = 1) {
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', 10);

        // 获取搜索条件
        const deptName = document.getElementById('deptTotalScoreSearch')?.value;
        const scoreRange = document.getElementById('deptScoreRangeSearch')?.value;
        if (deptName) params.append('bcpbm', deptName);
        if (scoreRange) params.append('scoreRange', scoreRange);

        CommonModule.apiRequest(`/score/dept/list?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderDeptTotalScoresTable(data.data.records || []);
                    // 确保分页组件正确显示
                    const paginationContainer = document.getElementById('deptTotalScoresPagination');
                    if (paginationContainer && data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 10);
                        if (totalPages > 1) {
                            CommonModule.createPagination('deptTotalScoresPagination', totalPages, page, (p) => this.loadDeptTotalScores(p));
                        } else {
                            // 如果只有一页，清空分页容器
                            paginationContainer.innerHTML = '';
                        }
                    } else if (paginationContainer) {
                        paginationContainer.innerHTML = '';
                    }
                } else {
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载部门总分');
                    // 清空分页容器
                    const paginationContainer = document.getElementById('deptTotalScoresPagination');
                    if (paginationContainer) {
                        paginationContainer.innerHTML = '';
                    }
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载部门总分');
                // 清空分页容器
                const paginationContainer = document.getElementById('deptTotalScoresPagination');
                if (paginationContainer) {
                    paginationContainer.innerHTML = '';
                }
            });
    },

    renderDeptTotalScoresTable(scores) {
        const container = document.getElementById('deptTotalScoresTableContent');
        if (!container) return;

        if (scores && scores.length > 0) {
            let html = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>部门编号</th>
                            <th>部门名称</th>
                            <th>总分</th>
                            <th>排名</th>
                            <!--th>操作</th-->
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            scores.forEach((score, index) => {
                // 确保分数格式化为一位小数
                const formattedScore = parseFloat(score.totalScore || score.score || 0).toFixed(1);
                html += `
                    <tr>
                        <td>${score.bmbh || ''}</td>
                        <td>${score.bmmc || score.bcpbm || ''}</td>
                        <td>${formattedScore}</td>
                        <td>${index + 1}</td>
                        <!--td>
                            <button class="btn btn-primary btn-small" onclick="EvaluationScoreModule.viewDeptScore('${score.bcpbm}')">查看详情</button>
                        </td-->
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            container.innerHTML = html;
        } else {
            container.innerHTML = '<div class="empty">暂无数据</div>';
        }
    },

    // ========== 教师指标分数 ==========
    loadTeacherIndicatorScores(page = 1) {
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', 10);

        // 获取搜索条件
        const teacherName = document.getElementById('teacherIndicatorScoreSearch')?.value;
        const indicatorId = document.getElementById('teacherIndicatorTypeSearch')?.value;
        if (teacherName) params.append('teacherName', teacherName);
        if (indicatorId) params.append('indicatorId', indicatorId);

        CommonModule.apiRequest(`/score/teacher-indicator-scores?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderTeacherIndicatorScoresTable(data.data.list || []);
                    // 处理分页
                    const paginationContainer = document.getElementById('teacherIndicatorScoresPagination');
                    if (paginationContainer && data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 10);
                        if (totalPages > 1) {
                            CommonModule.createPagination('teacherIndicatorScoresPagination', totalPages, page, (p) => this.loadTeacherIndicatorScores(p));
                        } else {
                            paginationContainer.innerHTML = '';
                        }
                    } else if (paginationContainer) {
                        paginationContainer.innerHTML = '';
                    }
                } else {
                    const container = document.getElementById('teacherIndicatorScoresTableContent');
                    if (container) {
                        container.innerHTML = '<div class="error">加载失败：' + (data.message || '未知错误') + '</div>';
                    }
                    // 清空分页容器
                    const paginationContainer = document.getElementById('teacherIndicatorScoresPagination');
                    if (paginationContainer) {
                        paginationContainer.innerHTML = '';
                    }
                }
            })
            .catch(error => {
                const container = document.getElementById('teacherIndicatorScoresTableContent');
                if (container) {
                    container.innerHTML = '<div class="error">网络错误，请稍后重试</div>';
                }
                // 清空分页容器
                const paginationContainer = document.getElementById('teacherIndicatorScoresPagination');
                if (paginationContainer) {
                    paginationContainer.innerHTML = '';
                }
            });
    },

    renderTeacherIndicatorScoresTable(scores) {
        const container = document.getElementById('teacherIndicatorScoresTableContent');
        if (!container) return;

        if (scores && scores.length > 0) {
            let html = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>教师编号</th>
                            <th>教师工号</th>
                            <th>教师姓名</th>
                            <th>指标编号</th>
                            <th>测评权重编号</th>
                            <th>测评权重名称</th>
                            <th>测评指标权重</th>
                            <th>分数</th>
                            <!--th>操作</th-->
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            scores.forEach(score => {
                html += `
                    <tr>
                        <td>${score.jsbh || score.bcpjs || ''}</td>
                        <td>${score.jsgh || ''}</td>
                        <td>${score.jsxm || ''}</td>
                        <td>${score.zbbh || score.cpzbbh || ''}</td>
                        <td>${score.cpqzbh || ''}</td>
                        <td>${score.cpqzmc || ''}</td>
                        <td>${score.cpzbqz || ''}</td>
                        <td class="score-value">${score.score || '0'}</td>
                        <!--td>
                            <button class="btn btn-primary btn-small" onclick="EvaluationScoreModule.viewTeacherIndicatorScore('${score.bh}')">查看详情</button>
                        </td-->
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            container.innerHTML = html;
        } else {
            container.innerHTML = '<div class="empty">暂无数据</div>';
        }
    },

    // ========== 教师总分 ==========
    loadTeacherTotalScores(page = 1) {
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', 10);

        // 获取搜索条件
        const teacherName = document.getElementById('teacherTotalScoreSearch')?.value;
        const deptName = document.getElementById('teacherScoreDeptSearch')?.value;
        const scoreRange = document.getElementById('teacherScoreRangeSearch')?.value;
        if (teacherName) params.append('teacherName', teacherName);
        if (deptName) params.append('deptName', deptName);
        if (scoreRange) params.append('scoreRange', scoreRange);

        CommonModule.apiRequest(`/score/teacher-total-scores?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderTeacherTotalScoresTable(data.data.list || data.data.records || []);
                    // 处理分页
                    const paginationContainer = document.getElementById('teacherTotalScoresPagination');
                    if (paginationContainer && data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 10);
                        if (totalPages > 1) {
                            CommonModule.createPagination('teacherTotalScoresPagination', totalPages, page, (p) => this.loadTeacherTotalScores(p));
                        } else {
                            paginationContainer.innerHTML = '';
                        }
                    } else if (paginationContainer) {
                        paginationContainer.innerHTML = '';
                    }
                } else {
                    const container = document.getElementById('teacherTotalScoresTableContent');
                    if (container) {
                        container.innerHTML = '<div class="error">加载失败：' + (data.message || '未知错误') + '</div>';
                    }
                    // 清空分页容器
                    const paginationContainer = document.getElementById('teacherTotalScoresPagination');
                    if (paginationContainer) {
                        paginationContainer.innerHTML = '';
                    }
                }
            })
            .catch(error => {
                const container = document.getElementById('teacherTotalScoresTableContent');
                if (container) {
                    container.innerHTML = '<div class="error">网络错误，请稍后重试</div>';
                }
                // 清空分页容器
                const paginationContainer = document.getElementById('teacherTotalScoresPagination');
                if (paginationContainer) {
                    paginationContainer.innerHTML = '';
                }
            });
    },

    renderTeacherTotalScoresTable(scores) {
        const container = document.getElementById('teacherTotalScoresTableContent');
        if (!container) return;

        if (scores && scores.length > 0) {
            let html = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>教师编号</th>
                            <th>教师姓名</th>
                            <th>部门</th>
                            <th>总分</th>
                            <th>排名</th>
                            <!--th>操作</th-->
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            scores.forEach((score, index) => {
                html += `
                    <tr>
                        <td>${score.jsbh || ''}</td>
                        <td>${score.jsxm || score.bcpjs || ''}</td>
                        <td>${score.bmmc || ''}</td>
                        <td>${score.totalScore || '0'}</td>
                        <td>${index + 1}</td>
                        <!--td>
                            <button class="btn btn-primary btn-small" onclick="EvaluationScoreModule.viewTeacherScore('${score.bcpjs}')">查看详情</button>
                        </td-->
                    </tr>
                `;
            });
            
            html += `
                    </tbody>
                </table>
            `;
            
            container.innerHTML = html;
        } else {
            container.innerHTML = '<div class="empty">暂无数据</div>';
        }
    },

    viewTeacherIndicatorScore(bh) {
        console.log('查看教师指标分数详情:', bh);
        // TODO: 实现教师指标分数详情查看功能
        alert('查看教师指标分数详情功能开发中...');
    },

    viewTeacherScore(teacherCode) {
        console.log('查看教师总分详情:', teacherCode);
        // TODO: 实现教师总分详情查看功能
        alert('查看教师总分详情功能开发中...');
    },

    searchDeptTotalScores() {
        this.loadDeptTotalScores(1);
    },

    exportDeptTotalScores() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/dept-total-scores';
    },

    searchTeacherIndicatorScores() {
        this.loadTeacherIndicatorScores(1);
    },

    exportTeacherIndicatorScores() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/teacher-indicator-scores';
    },

    searchTeacherTotalScores() {
        this.loadTeacherTotalScores(1);
    },

    exportTeacherTotalScores() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/teacher-total-scores';
    },

    // ========== 分数计算功能 ==========
    calculateDeptIndicatorScores() {
        if (!CommonModule.confirmAction('确认计算部门指标分数？此操作将重新计算所有部门的指标分数。')) {
            return;
        }

        CommonModule.apiRequest('/score/calculate-dept-indicator-scores', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('部门指标分数计算完成：' + data.message);
                this.loadDeptIndicatorScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算部门指标分数');
        });
    },

    calculateDeptTotalScores() {
        if (!CommonModule.confirmAction('确认计算部门总分？此操作将重新计算所有部门的总分。')) {
            return;
        }

        CommonModule.apiRequest('/score/calculate-dept-total-scores', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('部门总分计算完成：' + data.message);
                this.loadDeptTotalScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算部门总分');
        });
    },

    calculateTeacherIndicatorScores() {
        if (!CommonModule.confirmAction('确认计算教师指标分数？此操作将重新计算所有教师的指标分数。')) {
            return;
        }

        CommonModule.apiRequest('/score/calculate-teacher-indicator-scores', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('教师指标分数计算完成：' + data.message);
                this.loadTeacherIndicatorScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算教师指标分数');
        });
    },

    calculateTeacherTotalScores() {
        if (!CommonModule.confirmAction('确认计算教师总分？此操作将重新计算所有教师的总分。')) {
            return;
        }

        CommonModule.apiRequest('/score/calculate-teacher-total-scores', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('教师总分计算完成：' + data.message);
                this.loadTeacherTotalScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算教师总分');
        });
    },

    resetDeptScores() {
        if (!CommonModule.confirmAction('确认重置部门分数？此操作将清空所有部门分数数据，不可恢复！')) {
            return;
        }

        CommonModule.apiRequest('/score/reset-dept-scores', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('部门分数重置完成');
                this.loadDeptIndicatorScores();
                this.loadDeptTotalScores();
            } else {
                alert('重置失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '重置部门分数');
        });
    },

    resetTeacherScores() {
        if (!CommonModule.confirmAction('确认重置教师分数？此操作将清空所有教师分数数据，不可恢复！')) {
            return;
        }

        CommonModule.apiRequest('/score/reset-teacher-scores', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('教师分数重置完成');
                this.loadTeacherIndicatorScores();
                this.loadTeacherTotalScores();
            } else {
                alert('重置失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '重置教师分数');
        });
    },

    // 计算部门指标分数
    calculateDeptIndicatorScores() {
        if (!confirm('确认计算部门指标分数？此操作将重新计算所有部门指标分数！')) {
            return;
        }

        CommonModule.apiRequest('/score/dept/calculate', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('部门指标分数计算完成');
                this.loadDeptIndicatorScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算部门指标分数');
        });
    },

    // 计算部门总分
    calculateDeptTotalScores() {
        if (!confirm('确认计算部门总分？此操作将重新计算所有部门总分！')) {
            return;
        }

        CommonModule.apiRequest('/score/dept/calculate-total', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('部门总分计算完成');
                this.loadDeptTotalScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算部门总分');
        });
    },

    // 计算教师指标分数
    calculateTeacherIndicatorScores() {
        if (!confirm('确认计算教师指标分数？此操作将重新计算所有教师指标分数！')) {
            return;
        }

        CommonModule.apiRequest('/score/teacher/calculate', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('教师指标分数计算完成');
                this.loadTeacherIndicatorScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算教师指标分数');
        });
    },

    // 计算教师总分
    calculateTeacherTotalScores() {
        if (!confirm('确认计算教师总分？此操作将重新计算所有教师总分！')) {
            return;
        }

        CommonModule.apiRequest('/score/teacher/calculate-total', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('教师总分计算完成');
                this.loadTeacherTotalScores();
            } else {
                alert('计算失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '计算教师总分');
        });
    },

    // 重置部门分数
    resetDeptScores() {
        if (!confirm('确认重置部门分数？此操作将清空所有部门分数数据，不可恢复！')) {
            return;
        }

        CommonModule.apiRequest('/score/reset-dept-scores', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('部门分数重置完成');
                this.loadDeptIndicatorScores();
                this.loadDeptTotalScores();
            } else {
                alert('重置失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '重置部门分数');
        });
    }
};

// 全局函数用于Tab切换
function switchScoreTab(tabName) {
    EvaluationScoreModule.switchTab(tabName);
}

// 全局搜索函数
function searchDeptIndicatorScores() {
    EvaluationScoreModule.searchDeptIndicatorScores();
}

function searchDeptTotalScores() {
    console.log('searchDeptTotalScores 被调用');
    
    // 优先使用 EvaluationScoreModule 的方法
    if (typeof EvaluationScoreModule !== 'undefined' && EvaluationScoreModule.loadDeptTotalScores) {
        EvaluationScoreModule.loadDeptTotalScores(1);
        return;
    }
    
    // 备用实现：直接搜索逻辑
    const params = new URLSearchParams();
    params.append('page', 1);
    params.append('size', 10);

    // 获取搜索条件
    const deptName = document.getElementById('deptTotalScoreSearch')?.value;
    const scoreRange = document.getElementById('deptScoreRangeSearch')?.value;
    if (deptName) params.append('bcpbm', deptName);
    if (scoreRange) params.append('scoreRange', scoreRange);

    // 使用 CommonModule 或者直接 fetch
    const apiUrl = (typeof CommonModule !== 'undefined' && CommonModule.globalConfig) 
        ? CommonModule.globalConfig.apiBase + `/score/dept/list?${params}`
        : `/evaluation/api/admin/score/dept/list?${params}`;
    
    console.log('请求URL:', apiUrl);
    
    fetch(apiUrl, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        console.log('搜索结果:', data);
        if (data.code === 200 && data.data) {
            renderDeptTotalScoresTableStandalone(data.data.records || []);
            
            // 处理分页
            const paginationContainer = document.getElementById('deptTotalScoresPagination');
            if (paginationContainer && data.data.total > 0) {
                const totalPages = Math.ceil(data.data.total / 10);
                if (totalPages > 1) {
                    // 创建简单的分页组件
                    createSimplePagination('deptTotalScoresPagination', totalPages, 1, searchDeptTotalScoresWithPage);
                } else {
                    paginationContainer.innerHTML = '';
                }
            } else if (paginationContainer) {
                paginationContainer.innerHTML = '';
            }
        } else {
            console.error('搜索失败:', data.message);
            alert('搜索失败：' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('搜索请求失败:', error);
        alert('搜索请求失败，请检查网络连接');
    });
}

// 独立的部门总分表格渲染函数
function renderDeptTotalScoresTableStandalone(scores) {
    const container = document.getElementById('deptTotalScoresTableContent');
    if (!container) {
        console.error('找不到容器元素 deptTotalScoresTableContent');
        return;
    }

    if (scores && scores.length > 0) {
        let html = `
            <table class="data-table">
                <thead>
                    <tr>
                        <th>部门编号</th>
                        <th>部门名称</th>
                        <th>总分</th>
                        <th>排名</th>
                        <!--th>操作</th-->
                    </tr>
                </thead>
                <tbody>
        `;
        
        scores.forEach((score, index) => {
            // 确保分数格式化为一位小数
            const formattedScore = parseFloat(score.totalScore || score.score || 0).toFixed(1);
            html += `
                <tr>
                    <td>${score.bmbh || ''}</td>
                    <td>${score.bmmc || score.bcpbm || ''}</td>
                    <td>${formattedScore}</td>
                    <td>${index + 1}</td>
                    <!--td>
                        <button class="btn btn-primary btn-small" onclick="alert('查看详情功能开发中')">查看详情</button>
                    </td-->
                </tr>
            `;
        });
        
        html += `
                </tbody>
            </table>
        `;
        
        container.innerHTML = html;
    } else {
        container.innerHTML = '<div class="empty">暂无数据</div>';
    }
}

function searchTeacherIndicatorScores() {
    EvaluationScoreModule.searchTeacherIndicatorScores();
}

function searchTeacherTotalScores() {
    EvaluationScoreModule.searchTeacherTotalScores();
}

// 全局导出函数
function exportDeptIndicatorScores() {
    EvaluationScoreModule.exportDeptIndicatorScores();
}

function exportDeptTotalScores() {
    EvaluationScoreModule.exportDeptTotalScores();
}

function exportTeacherIndicatorScores() {
    EvaluationScoreModule.exportTeacherIndicatorScores();
}

function exportTeacherTotalScores() {
    EvaluationScoreModule.exportTeacherTotalScores();
}

// 全局计算函数
function calculateDeptIndicatorScores() {
    EvaluationScoreModule.calculateDeptIndicatorScores();
}

function calculateDeptTotalScores() {
    EvaluationScoreModule.calculateDeptTotalScores();
}

function calculateTeacherIndicatorScores() {
    EvaluationScoreModule.calculateTeacherIndicatorScores();
}

function calculateTeacherTotalScores() {
    EvaluationScoreModule.calculateTeacherTotalScores();
}

function resetDeptScores() {
    EvaluationScoreModule.resetDeptScores();
}

function resetTeacherScores() {
    EvaluationScoreModule.resetTeacherScores();
}

// 简单的分页组件创建函数（备用）
function createSimplePagination(containerId, totalPages, currentPage, onPageChange) {
    const container = document.getElementById(containerId);
    if (!container) return;

    container.innerHTML = '';

    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.textContent = '上一页';
    prevBtn.className = 'pagination-btn';
    prevBtn.disabled = currentPage <= 1;
    prevBtn.onclick = () => {
        if (currentPage > 1) {
            onPageChange(currentPage - 1);
        }
    };
    container.appendChild(prevBtn);

    // 页码按钮
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.textContent = i;
        pageBtn.className = 'pagination-btn' + (i === currentPage ? ' active' : '');
        pageBtn.onclick = () => onPageChange(i);
        container.appendChild(pageBtn);
    }

    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.textContent = '下一页';
    nextBtn.className = 'pagination-btn';
    nextBtn.disabled = currentPage >= totalPages;
    nextBtn.onclick = () => {
        if (currentPage < totalPages) {
            onPageChange(currentPage + 1);
        }
    };
    container.appendChild(nextBtn);
}

// 带分页的搜索函数
function searchDeptTotalScoresWithPage(page) {
    const params = new URLSearchParams();
    params.append('page', page);
    params.append('size', 10);

    // 获取搜索条件
    const deptName = document.getElementById('deptTotalScoreSearch')?.value;
    const scoreRange = document.getElementById('deptScoreRangeSearch')?.value;
    if (deptName) params.append('bcpbm', deptName);
    if (scoreRange) params.append('scoreRange', scoreRange);

    const apiUrl = (typeof CommonModule !== 'undefined' && CommonModule.globalConfig) 
        ? CommonModule.globalConfig.apiBase + `/score/dept/list?${params}`
        : `/evaluation/api/admin/score/dept/list?${params}`;
    
    fetch(apiUrl, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200 && data.data) {
            renderDeptTotalScoresTableStandalone(data.data.records || []);
            
            // 处理分页
            const paginationContainer = document.getElementById('deptTotalScoresPagination');
            if (paginationContainer && data.data.total > 0) {
                const totalPages = Math.ceil(data.data.total / 10);
                if (totalPages > 1) {
                    createSimplePagination('deptTotalScoresPagination', totalPages, page, searchDeptTotalScoresWithPage);
                } else {
                    paginationContainer.innerHTML = '';
                }
            } else if (paginationContainer) {
                paginationContainer.innerHTML = '';
            }
        } else {
            console.error('搜索失败:', data.message);
            alert('搜索失败：' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('搜索请求失败:', error);
        alert('搜索请求失败，请检查网络连接');
    });
}

// 导出模块
window.EvaluationScoreModule = EvaluationScoreModule; 